package com.snjgm.request_network_server;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: snjgm
 * data: 2022/8/25
 * description:
 */
public class RequestNetWorkService extends Service {
    private static final String TAG = "RequestNetWorkService";
    private Messenger messenger = new Messenger(new MessengerHandler());
    private Messenger mClientMessenger;
    private URL url = null;
    private String mURL = "https://www.baidu.com";
    private HttpURLConnection connection;
    private int HTTP_SOCKET_TIMEOUT = 5000;
    private int responseStatusCode;
    private static final String ACTION_KEY = "action_type";
    private static final String RECEIER_INTENT_ACTION = "com.snjgm.request_network_server.intent.action.AlarmReceiver";
    private AlarmManager mAlarmManager = null;
    private PendingIntent pi;
//    private long mAlarmTime = 60 * 60 * 24 * 1000; //24h

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: 我是服务端");
        return messenger.getBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        Log.d(TAG, "onStartCommand:" + "acionType此时的值为" + actionType + "mClientMessenger" + mClientMessenger.toString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    startRequestHttp(Constants.MSG_FROM_SERVICE, mClientMessenger);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }


    private class MessengerHandler extends Handler {
        //这个方法是要我们主动重写的
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            mClientMessenger = msg.replyTo;
            int mClientWhat = msg.what;
            Log.d(TAG, "handleMessage: mClientWhat=="+mClientWhat);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (mClientWhat == Constants.MSG_FROM_CLIENT) {
                            startRequestHttp(Constants.MSG_FROM_SERVICE, mClientMessenger);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    /**
     * @param
     * @return author snjgm
     * time 2022/8/25 下午5:22
     * @description 访问网络的方法
     */
    private void startRequestHttp(int actionType, Messenger messenger) throws IOException {
        url = new URL(mURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(HTTP_SOCKET_TIMEOUT);
        connection.setReadTimeout(HTTP_SOCKET_TIMEOUT);
        connection.setRequestMethod("GET");
        Log.d(TAG, "startRequestHttp: 网络连接对象准备请求连接网络");
        connection.connect();
        Log.d(TAG, "startRequestHttp: 网络连接对象成功连接网络");
        responseStatusCode = connection.getResponseCode();
        Log.d(TAG, "toBaidu: respronseCode == " + responseStatusCode);
        if (responseStatusCode == 200) {
            //到下面这一步就完成了一次访问,对于结果我们将在结果处理方法中将其发送到客户端,形成一次访问闭环
            sendResultMessage(true, 200, actionType, messenger);
            setAlarm(Constants.MSG_FROM_SERVICE);
        }
       else {
            cancelAlarm(actionType);
            if (responseStatusCode == 403) {
                sendResultMessage(false, 403, actionType, messenger);
            } else {
                sendResultMessage(false, -1, actionType, messenger);
            }
        }
    }

    private void sendResultMessage(boolean authorized, int responseCode, int actionType, Messenger messenger) {
        if (messenger != null) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("authorized", authorized);
            bundle.putInt("response_code", responseCode);
            Message msg = Message.obtain();
            msg.what = actionType;
            msg.obj = bundle;
            //msg.setData(bundle);
            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                Log.e(TAG, "sendResultMessage Exception:" + e);
            }
        }
    }

    public void setAlarm(int actionType) {
        //设置显示意图,
        Log.d(TAG, "setAlarm: 执行了设置闹钟了");
        Intent intent = new Intent();
        intent.putExtra(ACTION_KEY, actionType);
        intent.setClass(this,AlarmReceiver.class);
        intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
        Log.d(TAG, "setAlarm中actionType == " + actionType);
        if (actionType == Constants.MSG_FROM_SERVICE) {
            intent.setAction(RECEIER_INTENT_ACTION);
            Log.d(TAG, "setAlarm: 进行了广播设置");
        }
        //设置延迟意图
        pi = PendingIntent.getBroadcast(this, 20, intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 2000, pi);
        Log.d(TAG, "setAlarm:已经通知了广播");
    }

    private void cancelAlarm(int actionType) {
        Log.d(TAG, "cancelAlarm actionType " + actionType);
        mAlarmManager.cancel(pi);
    }


}
